//
//  YKBrandsGridView.m
//  YKYintaiHD
//
//  Created by user on 12-3-26.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "YKBrandsGridView.h"
//#import "UrlImageView.h"
#define RGBACOLOR(_r, _g, _b, _a) [UIColor colorWithRed:(_r)/255.0 green:(_g)/255.0 blue:(_b)/255.0 alpha:(_a)]

@implementation YKBrandsGridView
@synthesize dataSource;
@synthesize delegate_grid;
@synthesize editing;
@synthesize headerView,footerView,headerHeight;
-(void) internalInit{
#pragma mark 俩字典！数据源！
	visibleCellDictionary=[[NSMutableDictionary  alloc] init];
	dequeArray=[[NSMutableDictionary alloc] init];
	self.clipsToBounds=YES;
    cellFrameArray=[[NSMutableArray alloc] init];
    revertFrameH= self.bounds.size.height;
    
}
-(id) initWithFrame:(CGRect)frame{
	if((self=[super initWithFrame:frame])){
        [self internalInit];
    }
	return self;
}
-(id) initWithCoder:(NSCoder *)aDecoder{
	if((self=[super initWithCoder:aDecoder])){
		[self internalInit];
	}
	return self;
}
-(void)revert{
    CGRect frame=CGRectMake(self.frame.origin.x, self.frame.origin.y, self.frame.size.width, revertFrameH);
    self.frame=frame;
}
//-(void)drawRect:(CGRect)rect{
//    [super drawRect:rect];
//    gridItemSize=[dataSource sizeOfGridViewItem:self];
//    _gridFlags.gridNumOfItems=[dataSource numOfGridViewItem:self];
//    _gridFlags.gridNumOfCol=((int)floor( self.bounds.size.width/gridItemSize.width)<1)?1:(int)floor( self.bounds.size.width/gridItemSize.width);
//    _gridFlags.gridNumOfRow=(int)ceil(_gridFlags.gridNumOfItems/(float)_gridFlags.gridNumOfCol);
//    _gridFlags.gridContentHeight=_gridFlags.gridNumOfRow*(gridItemSize.height);
//    _gridFlags.gridContentWidth=(_gridFlags.gridNumOfCol*gridItemSize.width<self.bounds.size.width)?self.bounds.size.width:_gridFlags.gridNumOfCol*gridItemSize.width;
//    _gridFlags.gridHspacer=(_gridFlags.gridContentWidth-(_gridFlags.gridNumOfCol*gridItemSize.width))/4.0;
//}
//怎样才能在这个方法执行之前找一个只会执行一次的方法,用来存放
-(void) layoutSubviews{
	NSAutoreleasePool* pool=[[NSAutoreleasePool alloc] init];
	////!! //NSLog(@"%s",__FUNCTION__);
    BOOL one=YES;
    if (one) {
        if (getRidOfAnimation) {
            
            if ([cellFrameArray count]!=0) {
                CGRect rect=CGRectMake(self.frame.origin.x, self.frame.origin.y, self.frame.size.width, 1500);
                self.frame=rect;
            }
            
        }
    }
    
	CGSize sz = [dataSource sizeOfGridViewItem:self];//!
	int numOfItems=[dataSource numOfGridViewItem:self];//!
	int numOfCol=(int)floor( self.bounds.size.width/sz.width);//
    
	if(numOfCol<1){numOfCol=1;}//!
	int numOfRow= (int)ceil(numOfItems/(float)numOfCol);//!
    
	float contentHeight=numOfRow*(sz.height);//!
	float contentWidth=numOfCol*sz.width;//算出contentSize
    
	if(contentWidth<self.bounds.size.width){
		contentWidth=self.bounds.size.width;
	}
	float hspacer=(contentWidth-(numOfCol*sz.width))/2.0;
	CGRect visibleRect;//可见rect
	visibleRect.origin=self.contentOffset;//（100，0）
	visibleRect.size=self.bounds.size;//（320，480）   nice rect
	@synchronized(visibleCellDictionary){//block 可见cell数组
        
        
		for(int i=0;i<numOfItems;++i){//遍历每个cell
			NSAutoreleasePool* pool2=[[NSAutoreleasePool alloc] init];
			int colindex=i%numOfCol;
            //希望计算的x＝
            float x=hspacer+sz.width*colindex;
            
			//float x=(colindex)*sz.width+hspacer*(colindex+1);
			int rowindex=floor(i/(float)numOfCol);
			float y=rowindex*sz.height+headerHeight;
            
			id indexKey=[NSNumber numberWithInt:i];  
			YKBrandsGridViewCell* cell=[visibleCellDictionary objectForKey:indexKey];//这个字典里面顺序排列每个cell，第一次去不出来
            
            CGRect cellFrame=CGRectMake(x, y, sz.width, sz.height);
            NSValue *value=[NSValue valueWithCGRect:cellFrame];
            
			if(CGRectIntersectsRect(visibleRect, cellFrame)){//当前cell的frame与可见rect做相交判断，如果相交成功调用这个
                
				if(nil==cell){
					cell=[dataSource gridView:self cellForIndex:i];
                    //                    if (colindex==0) {  
                    //                        //在每个cell下 绘制一个separater
                    //                        UIView *separatorView=[[UIView alloc] initWithFrame:CGRectMake(0-hspacer, sz.height, self.bounds.size.width, .5)];
                    //                        separatorView.backgroundColor=RGBACOLOR(0xb5,0xb5,0xb5,1.);
                    //                        [cell addSubview:separatorView];
                    //                        [cell bringSubviewToFront:separatorView];
                    //                        [separatorView release];
                    //                    } 
				}
                
				assert(cell!=nil);
				cell.index=i;
				cell.frame=cellFrame;
				[self addSubview:cell];	
                if (cellFrameArray!=nil&&getRidOfAnimation&&[cellFrameArray count]>i) {
                    
                    
					NSValue *oldValue=[cellFrameArray objectAtIndex:i];
					
                    if (![oldValue isEqualToValue:value]) {
						cell.frame=[oldValue CGRectValue];
						//减淡
						for (UIView *view in [cell subviews]) {
//							if([view isKindOfClass:[UrlImageView class]]){
//								continue;
//							}
                            view.alpha=0;
						}
                        
                        [UIView beginAnimations:nil context:nil];
                        [UIView setAnimationDuration:1];
                        
                        cell.frame=cellFrame;
                        if (one) {
                            one=NO;
                            [UIView setAnimationDelegate:self];
                            [UIView setAnimationDidStopSelector:@selector(revert)];
                        }
                        [UIView commitAnimations];
                        //减淡动画
                        
                        [UIView beginAnimations:nil context:nil];
                        [UIView setAnimationDuration:3.0];
                        for (UIView *view in [cell subviews]) {
                            //类型为urlimageview的控件不做动画
//							if([view isKindOfClass:[UrlImageView class]]){
//								continue;
//							}
                            
                            view.alpha=1;
						}
                        
                        [UIView commitAnimations];
                        
                        
                        [cellFrameArray replaceObjectAtIndex:i withObject:value];
                    }else{
                        [self revert];
                    }
					
                }
				[self sendSubviewToBack:cell];
				[cell addTarget:self action:@selector(onTouchDown:) forControlEvents:UIControlEventTouchDown];
				[cell addTarget:self action:@selector(onCellTouch:) forControlEvents:UIControlEventTouchUpInside];
                [cell addTarget:self action:@selector(onTouchUp:) forControlEvents:UIControlEventTouchUpInside];
                [cell addTarget:self action:@selector(onTouchOutSizeUp:) forControlEvents:UIControlEventTouchUpOutside];
				
				[visibleCellDictionary setObject:cell forKey:indexKey];
				assert(cell.superview==self);
				if(delegate_grid!=nil && [delegate_grid respondsToSelector:@selector(gridView:willDisplayCell:atIndex:)]){
					[delegate_grid gridView:self willDisplayCell:cell atIndex:i];
				}
			}else{
				if(cell!=nil){//判断到这个cell变为不可见了！！，如果这个cell存在！！取出identifier对应的队列
					id identifier=[cell reuseIdentifier];
					if(identifier!=nil){
						NSMutableArray* dequeCellArray=(NSMutableArray*)[dequeArray objectForKey:identifier];
						if(dequeCellArray==nil){
							dequeCellArray=[[[NSMutableArray alloc] init] autorelease];
							[dequeArray setObject:dequeCellArray forKey:identifier];
						}
						@synchronized(dequeCellArray){
							[dequeCellArray addObject:cell];
						}
					}
                    if ([dataSource respondsToSelector:@selector(cellWillDisAppear:)]) {
                        [dataSource cellWillDisAppear:cell];    
                    }
					[cell removeFromSuperview];
				}
				[visibleCellDictionary removeObjectForKey:indexKey];				
			}
            
            if (i==numOfItems-1) {
                getRidOfAnimation=NO;
            }
            if (i+1>[cellFrameArray count]) {
                [cellFrameArray addObject:value];
            }else {
                [cellFrameArray replaceObjectAtIndex:i withObject:value];
            }
            
			[pool2 release];
		}
        
	}
	self.contentSize=CGSizeMake(contentWidth, (contentHeight<self.bounds.size.height?self.bounds.size.height+1:contentHeight)+(footerView==nil?0:footerView.frame.size.height)+headerHeight);
    
    
	[pool release];
    [super layoutSubviews];
}

- (void) setHeaderView: (UIView *) newHeaderView
{
    
    
	if ( newHeaderView == headerView )
		return;
    
	[headerView removeFromSuperview];//.莫非
	[headerView release];//两次释放到底为了谁
    
	headerView = [newHeaderView retain];
	if ( headerView == nil )
	{
		headerHeight = 0.0;
	}
	else
	{
        headerView.frame=CGRectMake(0, 0, headerView.frame.size.width, headerView.frame.size.height);
		[self addSubview: headerView];
		headerHeight = headerView.frame.size.height;
        
        
	}
    
	//[self setNeedsLayout];
}

-(void) dealloc{
	[visibleCellDictionary release];visibleCellDictionary=nil;
	[dequeArray release];dequeArray=nil;
    [cellFrameArray release];cellFrameArray=nil;
	[super dealloc];
}

- (YKBrandsGridViewCell *) dequeueReusableCellWithIdentifier:(NSString *)identifier{
	NSAutoreleasePool* pool=[[NSAutoreleasePool alloc] init];
	YKBrandsGridViewCell* ret=nil;
	NSMutableArray* dequeCellArray=(NSMutableArray*)[dequeArray objectForKey:identifier];
	if(dequeCellArray!=nil ){
		@synchronized(dequeCellArray){
			if([dequeCellArray count]>0){
				ret=(YKBrandsGridViewCell*)[[dequeCellArray lastObject] retain];
				[dequeCellArray removeObject:ret];
			}
		}
	}
	[pool release];
	return [ret autorelease];
}
-(void)onTouchDown:(id)sender{
//	YKBrandsGridViewCell* cell=(YKBrandsGridViewCell*)sender;
//	if(delegate_grid!=nil && [delegate_grid respondsToSelector:@selector(gridView:didSelectCell:atIndex:)] ){
//		[delegate_grid gridView:self didSelectCell:cell atIndex:cell.index];
//	}
}
-(void) onCellTouch:(id) sender{
	////!! //NSLog(@"%s",__FUNCTION__);
	YKBrandsGridViewCell* cell=(YKBrandsGridViewCell*)sender;
	if(delegate_grid!=nil && [delegate_grid respondsToSelector:@selector(gridView:didSelectCell:atIndex:)] ){
		[delegate_grid gridView:self didSelectCell:cell atIndex:cell.index];
	}
}
-(void)onTouchUp:(id)sender{
    YKBrandsGridViewCell* cell = (YKBrandsGridViewCell*)sender;
    if (delegate_grid != nil && [delegate_grid respondsToSelector:@selector(gridView:didSelectCellUp:atIndex:)]) {
        [delegate_grid gridView:self didSelectCellUp:cell atIndex:cell.index];
    }
}
-(void)onTouchOutSizeUp:(id)sender{
    YKBrandsGridViewCell* cell = (YKBrandsGridViewCell*)sender;
    if (delegate_grid != nil && [delegate_grid respondsToSelector:@selector(gridView:didSelectCellOutSizeUp:atIndex:)]) {
        [delegate_grid gridView:self didSelectCellOutSizeUp:cell atIndex:cell.index];
    }
}

-(void) reloadCellAtIndex:(int)index{
	NSNumber* key=[NSNumber numberWithInt:index];
	YKBrandsGridViewCell* cell=[visibleCellDictionary objectForKey:key];
	if(nil!=cell){
		[cell removeFromSuperview];
		[visibleCellDictionary removeObjectForKey:key];
	}
	[self setNeedsLayout];
}

-(void) reloadFooter{
	[footerView removeFromSuperview];
	footerView=nil;
	[self setNeedsLayout];
}

-(void) reloadData{
    getRidOfAnimation=YES;
	for(id key in [visibleCellDictionary allKeys]){
		UIView* v=[visibleCellDictionary objectForKey:key];
		[v removeFromSuperview];
	}
    
	[dequeArray removeAllObjects];
	[visibleCellDictionary removeAllObjects];//字典都清空了 layout时应该取消一次所有下载! 如果不取消下载，应该卸载的urlimgview就无法dealloc，新的urlimgview会
	//[self scrollsToTop];
    [self setContentOffset:CGPointMake(0, 0) animated:NO];
    for (UIView *vv in [self subviews]) {
        [vv removeFromSuperview];
    }
    //权宜之计 sep
    //    UIView *separatorViewhead=[[UIView alloc] initWithFrame:CGRectMake(0, headerHeight-2, self.bounds.size.width, .5)];
    //    separatorViewhead.backgroundColor=RGBACOLOR(0xb5,0xb5,0xb5,1.);
    //    [self addSubview:separatorViewhead];
    //    [self bringSubviewToFront:separatorViewhead];
    //    [separatorViewhead release];
    
	[self setNeedsLayout];
    
}

@end
